<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="选择群" prop="groupId">
        <el-col :span="15">
          <el-form-item prop="groupId">
            <el-select v-model="queryParams.groupId" placeholder="请选择"
                       style="width: 180px" @change="handleQuery">
              <el-option
                  v-for="dict in userGroups"
                  :key="dict.id"
                  :label="dict.groupName"
                  :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="等级名称" prop="levelName">
        <el-input
            v-model="queryParams.levelName"
            placeholder="请输入等级名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="最低下限包含：比如前5名>=5" prop="scopeLow">-->
      <!--        <el-input-->
      <!--            v-model="queryParams.scopeLow"-->
      <!--            placeholder="请输入最低下限包含：比如前5名>=5"-->
      <!--            clearable-->
      <!--            @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="最大上限不包含：比如<0" prop="scopeHigh">-->
      <!--        <el-input-->
      <!--            v-model="queryParams.scopeHigh"-->
      <!--            placeholder="请输入最大上限不包含：比如<0"-->
      <!--            clearable-->
      <!--            @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="作用：比如前5名，要让5分，后5名，要+5分" prop="effect">-->
      <!--        <el-input-->
      <!--            v-model="queryParams.effect"-->
      <!--            placeholder="请输入作用：比如前5名，要让5分，后5名，要+5分"-->
      <!--            clearable-->
      <!--            @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="租户编号" prop="tenantId">-->
      <!--        <el-input-->
      <!--            v-model="queryParams.tenantId"-->
      <!--            placeholder="请输入租户编号"-->
      <!--            clearable-->
      <!--            @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">清空</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--            type="primary"-->
      <!--            plain-->
      <!--            icon="Plus"-->
      <!--            @click="handleAdd"-->
      <!--            v-hasPermi="['group:level:add']"-->
      <!--        >新增-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['group:level:update']"
        > {{ queryParams.groupId > 0 ? "修改" : "复制" }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['group:level:delete']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['group:level:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="levelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" align="center" prop="id"/>
      <el-table-column label="群名称" align="center" prop="groupName"/>
      <el-table-column label="等级名称" align="center" prop="levelName"/>
      <el-table-column label="最低(大于等于)" align="center" prop="scopeLow"/>
      <el-table-column label="最高(小于)" align="center" prop="scopeHigh"/>
      <el-table-column label="划分类型" align="center">
        <template #default="scope">
          <dict-tag :options="group_stipu_type" :value="scope.row.stipulationType"/>
        </template>
      </el-table-column>
      <el-table-column label="排名类型" align="center">
        <template #default="scope">
          <dict-tag :options="group_rank_type" :value="scope.row.rankType"/>
        </template>
      </el-table-column>
      <el-table-column label="让分" align="center" prop="effect"/>
      <el-table-column label="是否启用" align="center">
        <template #default="scope">
          <dict-tag :options="group_login_default" :value="scope.row.useStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-if="permitUpdate(scope.row.groupId)"
                     v-hasPermi="['group:level:update']">
            {{ scope.row.groupId === -1 ? "复制" : "修改" }}
          </el-button>
          <el-button v-if="scope.row.groupId !==-1 && permitUpdate(scope.row.groupId) " link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['group:level:delete']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!-- 添加或修改等级划分规则对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="levelRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="选择群" prop="groupId">
          <el-col :span="12">
            <el-form-item prop="groupId">
              <el-select v-model="form.groupId" placeholder="请选择" :disabled="form.id > 20 || queryParams.groupId">
                <el-option
                    v-for="dict in adminGroups"
                    :key="dict.id"
                    :label="dict.groupName"
                    :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="等级名称" prop="levelName">
          <el-input v-model="form.levelName" placeholder="请输入等级名称"/>
        </el-form-item>
        <el-form-item label="大于等于" prop="scopeLow">
          <el-input v-model="form.scopeLow" placeholder="请输入最低下限包含：比如前5名>=5"/>
        </el-form-item>
        <el-form-item label="小于" prop="scopeHigh">
          <el-input v-model="form.scopeHigh" placeholder="请输入最大上限不包含：比如<0"/>
        </el-form-item>
        <el-form-item label="让分" prop="effect">
          <el-input v-model="form.effect" placeholder="请输入作用：比如前5名，要让5分，后5名，要+5分"/>
        </el-form-item>
        <el-form-item label="启用状态：" label-width="95px">
          <el-form-item>
            <el-col :span="24">
              <el-form-item>
                <el-radio-group v-model="form.useStatus">
                  <el-radio
                      v-for="dict in group_login_default"
                      :key="dict.value"
                      :value="dict.value"
                  >{{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-form-item>
        </el-form-item>
        <!--        <el-form-item label="租户编号" prop="tenantId">-->
        <!--          <el-input v-model="form.tenantId" placeholder="请输入租户编号"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Level">
import * as levelApi from "@/api/group/level.js";
import {AES_Decrypt} from "@/utils/jsencrypt.js";
import * as groupServer from "@/api/group/group.js";

const route = useRoute();
const {proxy} = getCurrentInstance();
const {
  group_stipu_type,
  group_rank_type,
  group_login_default
} = proxy.useDict("group_stipu_type", "group_rank_type", "group_login_default");

const levelList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const groupId = ref(Number(AES_Decrypt(route.query.groupId)) === 0 ? undefined : Number(AES_Decrypt(route.query.groupId)));
const resetFlag = ref(false);
const userGroups = ref([])
const adminGroups = ref([])
const groupPermitMap = reactive(new Map())
const data = reactive({
  form: {},
  queryParams: {
    startTime: null,
    findTime: null,
    endTime: null,
    pageNum: 1,
    pageSize: 50,
    groupId: groupId.value,
    levelName: null,
    scopeLow: null,
    scopeHigh: null,
    stipulationType: null,
    rankType: null,
    effect: null,
    useStatus: null,
    tenantId: null,
  },
  rules: {
    groupId: [
      {required: true, message: "群id不能为空", trigger: "blur"}
    ],
    levelName: [
      {required: true, message: "等级名称不能为空", trigger: "blur"}
    ],
    scopeLow: [
      {required: true, message: "最低下限包含：比如前5名>=5不能为空", trigger: "blur"}
    ],
    scopeHigh: [
      {required: true, message: "最大上限不包含：比如<0不能为空", trigger: "blur"}
    ],
    stipulationType: [
      {required: true, message: "1.胜率 2.获得奖励 3.名次不能为空", trigger: "change"}
    ],
    effect: [
      {required: true, message: "作用：比如前5名，要让5分，后5名，要+5分不能为空", trigger: "blur"}
    ],
    useStatus: [
      {required: true, message: "是否有效：0:无效，1:有效不能为空", trigger: "change"}
    ],
    createTime: [
      {required: true, message: "创建时间不能为空", trigger: "blur"}
    ],
    updateTime: [
      {required: true, message: "更新时间不能为空", trigger: "blur"}
    ],
    deleted: [
      {required: true, message: "是否删除不能为空", trigger: "blur"}
    ],
    tenantId: [
      {required: true, message: "租户编号不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);
const start = (() => {
  return new Promise(resolve => {
    groupServer.callFindList(null).then(res => {
      userGroups.value = res.data
      adminGroups.value = [];
      userGroups.value.forEach(item => {
        if (item.adminType > 0) {
          adminGroups.value.push(item)
        }
        groupPermitMap.set(item.id, item.adminType)
      })
      //console.log("item.adminType", adminGroups.value);
      if (!groupId.value  && !resetFlag.value) {
        userGroups.value.forEach(item => {
          if (item.loginDefault === 1) {
            groupId.value = item.id
            queryParams.value.groupId = item.id
          }
        })
      }
      if (!groupId.value && !resetFlag.value) {
        groupId.value = userGroups.value[0].id
        queryParams.value.groupId = userGroups.value[0].id
      }
    }).then(() => {
      // //console.log("start",currentAdmin.value)
      resolve()
    })
  })
})

function permitUpdate(groupId) {
  return groupPermitMap.get(groupId)
}

/** 查询等级划分规则列表 */
function getList() {
  loading.value = true;
  start().then(() => {
    if (queryParams.value.findTime) {
      queryParams.value.endTime = queryParams.value.findTime[1]
      queryParams.value.startTime = queryParams.value.findTime[0]
    }
    levelApi.listLevel(queryParams.value).then(response => {
      levelList.value = response.data.list;
      total.value = response.data.total;
      loading.value = false;
    });
  })
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单清空
function reset() {
  form.value = {
    startTime: null,
    findTime: null,
    endTime: null,
    id: null,
    groupId: groupId.value ? groupId.value : null,
    levelName: null,
    scopeLow: null,
    scopeHigh: null,
    stipulationType: null,
    rankType: null,
    effect: null,
    useStatus: 0,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deleted: null,
    tenantId: null,
    remark: null
  };
  proxy.resetForm("levelRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 清空按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.groupId = undefined;
  form.value.groupId = undefined;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加等级划分规则";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value[0]
  levelApi.getLevel({id: _id}).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改等级划分规则";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["levelRef"].validate(valid => {
    if (valid) {
      //console.log("groupId----", form.value.groupId);
      //console.log("id----", form.value.id);
      if (form.value.id < 23) {
        form.value.id = null
      }
      if (form.value.id != null && form.value.groupId !== -1) {
        levelApi.updateLevel(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else if (form.value.groupId !== -1) {
        levelApi.addLevel([form.value]).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id ? [row.id] : ids.value;

  proxy.$modal.confirm('是否确认删除等级划分规则编号为"' + _ids + '"的数据项？').then(function () {
    return levelApi.delLevel({delIds: _ids});
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('group/level/export', {
    ...queryParams.value
  }, `level_${new Date().getTime()}.xlsx`)
}

getList();
</script>
